package com.sys.web.async;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sys.utils.*;
import com.sys.constant.*;
import com.sys.dao.DownLoadDao;
import com.sys.dao.impl.DownLoadImpl;
import com.sys.domain.Download;
import com.sys.service.impl.UploadOperationImpl;

@WebServlet("/homeAsy")
public class HomeAsy extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String method = request.getParameter("method");
		if(method.equals("download")) {
			try {
				download(request, response);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
	}

	/**
	 * @Title: download 
	 * @Description: TODO(同步下载) 
	 * @param request response
	 * @throws IOException
	 * @throws SQLException 
	 */
	private void download(HttpServletRequest request, HttpServletResponse response)
			throws IOException, SQLException {
		//获得文件名并解决乱码问题
		String fileId = new String(request.getParameter("fileId").getBytes("ISO-8859-1"),"UTF-8");
		//获得客户端信息
		String agent = request.getHeader("User-Agent");
		//处理不同客户端的文件名问题
		String fileNameEncoding = DownloadUtils.getDownloadFileName(fileId, agent);
		//告知浏览器这是一个下载，能解析和不能解析的文件都以附件形式下载
		response.setContentType(this.getServletContext().getMimeType(fileId));
		response.setHeader("Content-Disposition", "attachment;filename=\""+fileNameEncoding.substring(9)+"\"");
		//完整的文件下载路径
		String path = UploadAndDownloadPath.path+"\\"+fileId;
		ServletOutputStream out = response.getOutputStream();
		//文件由服务器拷贝至客户端
		InputStream inputStream = null;
		try {
			inputStream = new FileInputStream(path);
		} catch (FileNotFoundException e) {
			response.sendRedirect(request.getContextPath() +"/notFoundResource");
			return;
		}
		int len = 0;
		byte[] buffer = new byte[1024];
		while((len=inputStream.read(buffer))>0){
			out.write(buffer, 0, len);
		}
		inputStream.close();
		String user = (String) request.getSession().getAttribute("user");
		if(user!=null) {
			Download download = new Download();
			download.setFileId(fileId);
			download.setUserId(user);
			download.setDownTime(new UploadOperationImpl().getCurrentDate());
			DownLoadDao dDao = new DownLoadImpl();
			dDao.insertDownLoad(download);
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}